package net.jacqeush.mini.rpc.annotation.auto.register;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import net.jacqeush.mini.rpc.annotation.RpcComponentScan;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jacquesh
 * @version 1.0
 * @date 2020/10/18 1:35
 */
@Slf4j
public class RpcComponentScanRegister  implements ImportBeanDefinitionRegistrar {

    @SneakyThrows
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        log.info("RpcComponentScanRegister start configurations");
        AnnotationAttributes  annotationAttributes=AnnotationAttributes.
        fromMap(annotationMetadata.getAnnotationAttributes(RpcComponentScan.class.getName()));
        Map<String,Object> configurations = getConfigurations(annotationMetadata, annotationAttributes);
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder
                .genericBeanDefinition(RpcAnnotasionBeanPostProcessor.class);

        beanDefinitionBuilder.addConstructorArgValue(configurations);

        beanDefinitionBuilder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
                /* 注册备案自动配置*/
        AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
        BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinition,beanDefinitionRegistry);


        log.info("RpcComponentScanRegister end configurations");

    }

    private Map<String,Object> getConfigurations(AnnotationMetadata annotationMetadata, AnnotationAttributes annotationAttributes) throws Throwable {
      Map<String,Object> objectMap =new HashMap<String,Object>(10);

        List<String> basePackages= Arrays.asList(annotationAttributes.getStringArray("basePackages"));
        if (basePackages.isEmpty()){
            throw  new Throwable("the basePackages is must");
        }
        List<String> value= Arrays.asList(annotationAttributes.getStringArray("value"));
        List<String> basePackagesClass= Arrays.asList(annotationAttributes.getStringArray("basePackagesClass"));
        objectMap.put("basePackages",basePackages);
        objectMap.put("value",value);
        objectMap.put("basePackagesClass",basePackagesClass);
        return  objectMap;
    }
}
